package com.easy.common.util.auth;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class UsbKey {

	private static final char HEX_ARRAY[] = {
		'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
		'a', 'b', 'c', 'd', 'e', 'f'
	};

	public UsbKey()
	{
	}

	public static byte[] md5(byte srcBytes[])
		throws Exception
	{
		MessageDigest md = null;
		try
		{
			md = MessageDigest.getInstance("MD5");
		}
		catch (NoSuchAlgorithmException ex)
		{
			throw ex;
		}
		md.update(srcBytes);
		return md.digest();
	}

	public static String md5Hex(byte srcBytes[])
		throws Exception
	{
		byte md5Array[] = md5(srcBytes);
		String rtStr = "";
		for (int i = 0; i < md5Array.length; i++)
		{
			byte high = (byte)(md5Array[i] >> 4 & 0xf);
			byte low = (byte)(md5Array[i] & 0xf);
			rtStr = (new StringBuilder(String.valueOf(rtStr))).append(HEX_ARRAY[high]).toString();
			rtStr = (new StringBuilder(String.valueOf(rtStr))).append(HEX_ARRAY[low]).toString();
		}

		return rtStr;
	}

	public static byte[] str2Bytes(String srcStr)
	{
		int len = srcStr.length();
		byte rtArray[] = new byte[len];
		for (int i = 0; i < len; i++)
			rtArray[i] = (byte)(srcStr.charAt(i) & 0xff);

		return rtArray;
	}

	public static String md5Hex(String srcStr)
		throws Exception
	{
		return md5Hex(str2Bytes(srcStr));
	}

	public static boolean digestComp(String clientDigest, String randomData, String passWord)
		throws Exception
	{
		String iPad = "";
		for (int i = 0; i < 64; i++)
			iPad = (new StringBuilder(String.valueOf(iPad))).append("6").toString();

		String oPad = "";
		for (int i = 0; i < 64; i++)
			oPad = (new StringBuilder(String.valueOf(oPad))).append("\\").toString();

		int keyLen = passWord.length();
		int randomLength = randomData.length();
		byte iResult[] = new byte[64 + randomLength];
		for (int i = 0; i < 64; i++)
			if (i < keyLen)
				iResult[i] = (byte)(iPad.charAt(i) & 0xff ^ passWord.charAt(i) & 0xff);
			else
				iResult[i] = (byte)(iPad.charAt(i) & 0xff);

		for (int i = 0; i < randomLength; i++)
			iResult[64 + i] = (byte)(randomData.charAt(i) & 0xff);

		iResult = md5(iResult);
		byte oResult[] = new byte[64 + iResult.length];
		for (int i = 0; i < 64; i++)
			if (i < keyLen)
				oResult[i] = (byte)(oPad.charAt(i) & 0xff ^ passWord.charAt(i) & 0xff);
			else
				oResult[i] = (byte)(oPad.charAt(i) & 0xff);

		for (int i = 0; i < iResult.length; i++)
			oResult[64 + i] = iResult[i];

		String result = md5Hex(oResult);
		result = result.toUpperCase();
		return result.equals(clientDigest);
	}

}
